package device

import (
	"backend/internal/common/errorx"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OpenConnectionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOpenConnectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OpenConnectionLogic {
	return &OpenConnectionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OpenConnectionLogic) OpenConnection(req *types.OpenConnectionReq) (resp *types.OpenConnectionResp, err error) {
	// 获取设备
	client := l.svcCtx.ClientManager.GetClient(req.DeviceName)
	if client == nil {
		errorStr := fmt.Sprintf("设备 %s 不存在", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusNotFound, "无法找到该设备")
	}

	// 直接调用 Connect 方法，因为该方法内部已实现多线程
	if !client.Connect() {
		errorStr := fmt.Sprintf("连接设备 %s 失败", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusInternalServerError, "无法连接到设备")
	}

	// 返回成功响应
	resp = &types.OpenConnectionResp{
		Status: http.StatusOK,
		Msg:    "成功连接到设备",
		Data:   true,
	}
	return resp, nil
}
